import {
  Controller,
  Post,
  Get,
  Body,
  Query,
  UseGuards,
  Request,
  HttpCode,
  HttpStatus,
  Logger,
  Res,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { AdminGuard } from '../auth/guards/admin.guard';
import { DeviceAuditService } from './device-audit.service';
import {
  PreinstalledLicenseRequestDto,
  PreinstalledLicenseResponseDto,
  AuditStatusRequestDto,
  AuditStatusResponseDto,
} from './dto/preinstalled-license.dto';
import {
  BatchAuditCodeGenerationRequestDto,
  BatchAuditCodeGenerationResponseDto,
} from './dto/audit-code-generation.dto';
import { JwtPayload } from '../auth/interfaces/jwt-payload.interface';
import { Response } from 'express';

@ApiTags('Device Audit')
@Controller()
export class DeviceAuditController {
  private readonly logger = new Logger(DeviceAuditController.name);

  constructor(private readonly deviceAuditService: DeviceAuditService) {}

  @Post('preinstalled/license')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '预装授权请求' })
  @ApiResponse({
    status: 200,
    description: '设备审核状态',
    type: PreinstalledLicenseResponseDto,
  })
  @ApiResponse({ status: 400, description: '无效请求' })
  @ApiResponse({ status: 404, description: '审核码或设备未找到' })
  @ApiResponse({ status: 409, description: '审核码已使用' })
  async verifyLicense(
    @Body() requestDto: PreinstalledLicenseRequestDto,
  ): Promise<PreinstalledLicenseResponseDto> {
    this.logger.log(
      `Received license verification request for audit number: ${requestDto.auditNumber}`,
    );

    return this.deviceAuditService.verifyAndCreateDevice(
      requestDto.auditNumber,
      requestDto.verifyCode,
      requestDto.deviceSerialNumber,
      requestDto.deviceMeta,
    );
  }

  @Get('audit/status')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '授权状态查询' })
  @ApiResponse({
    status: 200,
    description: '设备审核状态',
    type: AuditStatusResponseDto,
  })
  @ApiResponse({ status: 404, description: '设备未找到' })
  async getAuditStatus(
    @Query() requestDto: AuditStatusRequestDto,
  ): Promise<AuditStatusResponseDto> {
    this.logger.log(`Received audit status request for device: ${requestDto.deviceSerialNumber}`);

    return this.deviceAuditService.getAuditStatus(requestDto.deviceSerialNumber);
  }

  @Post('audit-codes/generate')
  @HttpCode(HttpStatus.CREATED)
  @UseGuards(JwtAuthGuard, AdminGuard)
  @ApiBearerAuth()
  @ApiOperation({
    summary: '生成审核码',
    description: '需要管理员权限 (ADMIN role)',
  })
  @ApiResponse({
    status: 201,
    description: '审核码生成成功',
    schema: {
      type: 'object',
      properties: {
        auditNumber: { type: 'string', example: 'AUDIT-12345678' },
        verifyCode: { type: 'string', example: 'VERIFY-87654321' },
      },
    },
  })
  @ApiResponse({ status: 401, description: '未认证或Token无效' })
  @ApiResponse({ status: 403, description: '无权限 (需要ADMIN角色)' })
  async generateAuditCode(@Request() req: { user: JwtPayload }) {
    this.logger.log(`Admin ${req.user.userId} requested to generate new audit code`);
    return this.deviceAuditService.generateAuditCode(req.user.userId);
  }

  @Post('audit-codes/generate-batch')
  @HttpCode(HttpStatus.CREATED)
  @UseGuards(JwtAuthGuard, AdminGuard)
  @ApiBearerAuth()
  @ApiOperation({
    summary: '批量生成审核码',
    description: '需要管理员权限 (ADMIN role)，最多生成100个审核码',
  })
  @ApiResponse({
    status: 201,
    description: '审核码批量生成成功',
    type: BatchAuditCodeGenerationResponseDto,
  })
  @ApiResponse({ status: 400, description: '无效请求，数量必须大于0且为整数' })
  @ApiResponse({ status: 401, description: '未认证或Token无效' })
  @ApiResponse({ status: 403, description: '无权限 (需要ADMIN角色)' })
  async generateAuditCodesBatch(
    @Request() req: { user: JwtPayload },
    @Body() requestDto: BatchAuditCodeGenerationRequestDto,
  ): Promise<BatchAuditCodeGenerationResponseDto> {
    this.logger.log(
      `Admin ${req.user.userId} requested to generate ${requestDto.count} audit codes in batch`,
    );
    const codes = await this.deviceAuditService.generateAuditCodesBatch(
      req.user.userId,
      requestDto.count,
    );
    return { codes };
  }

  @Get('audit-codes/export')
  @UseGuards(JwtAuthGuard, AdminGuard)
  @ApiBearerAuth()
  @ApiOperation({
    summary: '导出所有审核码为CSV格式',
    description: '需要管理员权限 (ADMIN role)',
  })
  @ApiResponse({
    status: 200,
    description: 'CSV文件下载',
    content: {
      'text/csv': {
        schema: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  @ApiResponse({ status: 401, description: '未认证或Token无效' })
  @ApiResponse({ status: 403, description: '无权限 (需要ADMIN角色)' })
  async exportAuditCodes(@Request() req: { user: JwtPayload }, @Res() res: Response) {
    this.logger.log(`Admin ${req.user.userId} requested to export audit codes to CSV`);

    // Get the CSV data
    const csvData = await this.deviceAuditService.exportAuditCodesToCSV();

    // Set headers for file download
    res.setHeader('Content-Type', 'text/csv');
    res.setHeader('Content-Disposition', 'attachment; filename=audit-codes.csv');

    // Send the CSV data
    return res.send(csvData);
  }
}
